const router = require('express').Router()
const U = require('../utils')
const Article = require('../models/Article')
const R = require('ramda')

router.param('id',(req,res,next,id) => {
  req.nodeId = id
  next()
})

function with_params(req,res,next){
  console.log("body: " + JSON.stringify(req.body))
  if(R.or(R.isNil(req.body.title), R.isNil(req.body.content))){
    res.json(U.err('请保证参数正确!'))
    return
  }
  next()
}

router.route('/:id')
 .get((req,res,next) => {
   console.log('获取article信息: '+req.nodeId)

   Article.get_with_default(req.nodeId).then(article => {
     res.json(U.ok(article))
   })
 })
 .put(with_params,(req,res,next) => {
   Article.update_by_node(req.nodeId,req.body.title,req.body.content).then(result => {
     res.json(U.ok('更新成功'))
   })
 })
 .delete((req,res,next) => {
   const articleId = req.nodeId
   Article.del(articleId).then(result => {
     res.json(U.ok('删除操作结束'))
   })
 })

module.exports = router